<?php
class ContactService extends My_Service
{   
    
    protected function check()
    {	
    	//validate ContactName
		$nameVald = new Zend_Validate_StringLength(1, 50);
		if(!$nameVald->isValid($_POST['contactName']))
		{
			$this->_errorList["contactName"] = My_Message::get("S002|Contact name|1|50");
		}
		
    	//validate image
		if(!empty($_FILES['imageURL']['name']))
		{
			$adapter = new Zend_File_Transfer_Adapter_Http();

			$adapter->addValidator('IsImage', false);
			if(!$adapter->isValid())
			{
				$this->_errorList["imageURL"] = My_Message::get("S004");
				return false;
			}

			$uploadDir = ARTICLE_IMG_UPLOAD_PATH;
			if(!is_readable($uploadDir))
			{
				$this->_errorList["imageURL"] = My_Message::get("S005|Image");
				return false;
			}
			
			$adapter->setDestination ($uploadDir);
			if (! $adapter->receive ()) {
				$this->_errorList["imageURL"] = My_Message::get("S005|Image");
				return false;
			}
		}
		
		if(empty($this->_errorList) == false)
		{
			return false;
		}
		return true;
    }
    
	public function bind()
	{
		$contact = new ContactDTO( );
		if(!empty($_POST['contactId']))//case edit
		{
			$contact = $this->load($_POST['contactId']);
		}
		
		$contact->contactName = $_POST['contactName'];
		
		if (! empty ( $_FILES ['imageURL']['name'] )) 
		{
			if(!empty($_POST['contactId']))//case edit, remove old images
			{
				$uploadDir = ARTICLE_IMG_UPLOAD_PATH;
				$imgFile = $uploadDir.$contact->imageURL;
				@unlink($imgFile);
			}
			$contact->imageURL = basename ( $_FILES ['imageURL'] ['name'] );
		}
		
		$contact->link = $_POST['link'];
		
		return $contact;
	}
    
    public function store()
    {
    	//check input data
    	if(!$this->check()){
			return false;
    	}
    	
    	//bind data
    	$contact = $this->bind();
    	
    	//save data
    	$this->save($contact);
    	return true;
    }
    
    
}
?>